package com.example.supernote.ui.manager

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.example.supernote.R
import com.example.supernote.model.manager.FileType
import com.example.supernote.model.manager.NoteTemplateType
import com.example.supernote.ui.components.UniformButton
import com.example.supernote.ui.components.UniformToast
import com.example.supernote.ui.note.components.ShowGeneratorDialog
import com.example.supernote.ui.utils.getSystemPrompt

@Composable
fun CreateFileButton(
    generateNoteTemplateByPrompt: ((String) -> Unit, Map<String, String>) -> Unit,
    createFolder: (String) -> Unit,
    createFile: (String, String) -> Unit
) {
    val toastContext = LocalContext.current
    var isVisible by remember {
        mutableStateOf(false)
    }
    var step by remember {
        mutableStateOf(0)
    }

    var template by remember {
        mutableStateOf("")
    }
    Box(modifier = Modifier.fillMaxSize()) {
        Button(
            onClick = { isVisible = true },
            modifier = Modifier
                .padding(bottom = 32.dp, end = 32.dp)
                .width(64.dp)
                .height(64.dp)
                .align(Alignment.BottomEnd),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.primary,
                contentColor = MaterialTheme.colorScheme.surface
            ),
            contentPadding = PaddingValues(0.dp)
        ) {
            Icon(
                modifier = Modifier.size(48.dp),
                imageVector = Icons.Filled.Add,
                contentDescription = "",
                tint = MaterialTheme.colorScheme.surface
            )
        }
    }
    if (isVisible) {
        when (step) {
            0 -> ChooseCreateType(onConfirm = {
                if (it == FileType.FILE) {
                    step = 2
                } else {
                    step = 1
                }
            }, onCancel = {
                isVisible = false
            })

            1 -> FinalCreateDialog(
                fileType = FileType.FOLDER,
                onConfirm = {
                    createFolder(it)
                    isVisible = false
                    step = 0
                }, onCancel = {
                    step = 0
                })

            2 -> CreateFileDialog(onConfirm = {
                if (it == NoteTemplateType.NO_TEMPLATE) {
                    step = 4
                } else {
                    step = 3
                }
            }, onCancel = {
                step = 0
            })

            3 -> {
                val dialogTitle = stringResource(R.string.manage_create)
                ShowGeneratorDialog(
                    onCancel = {
                        template = ""
                        step = 2
                    },
                    onGenerate = generateNoteTemplateByPrompt,
                    onConfirm = {
                        template = it
                        step = 4
                    },
                    otherInfos = mapOf(
                        "dialogTitle" to dialogTitle,
                        "systemPrompt" to getSystemPrompt(dialogTitle),
                        "inputLabel" to stringResource(R.string.manage_create_label)
                    )
                )
            }

            4 -> {
                val info = stringResource(R.string.note_has_created)
                FinalCreateDialog(
                    fileType = FileType.FILE,
                    onConfirm = {
                        createFile(template, it)
                        template = ""
                        isVisible = false
                        step = 0
                        UniformToast(toastContext, info)
                    }) {
                    step = 2
                }
            }
        }

    }
}


@Composable
fun BaseCreateDialog(title: String, onDismissRequest: () -> Unit, content: @Composable () -> Unit) {
    Dialog(
        onDismissRequest = onDismissRequest, properties = DialogProperties(
            dismissOnBackPress = true, dismissOnClickOutside = false
        )
    ) {
        Column(
            modifier = Modifier
                .background(MaterialTheme.colorScheme.background)
                .fillMaxWidth()
                .padding(10.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = title,
                modifier = Modifier.padding(5.dp),
                style = MaterialTheme.typography.titleLarge,
                color = MaterialTheme.colorScheme.onBackground
            )
            content()
        }
    }
}

@Composable
fun ChooseCreateType(onConfirm: (FileType) -> Unit, onCancel: () -> Unit) {
    var fileType by remember {
        mutableStateOf(FileType.FILE)
    }
    BaseCreateDialog(title = stringResource(id = R.string.cre_newContent), onDismissRequest = onCancel) {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier
                    .padding(5.dp)
                    .clickable(onClick = {
                        fileType = FileType.FILE
                    }), verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButton(
                    selected = fileType == FileType.FILE,
                    onClick = null
                )
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = stringResource(id = R.string.cre_note), color = MaterialTheme.colorScheme.onBackground)
            }
            Row(
                modifier = Modifier
                    .padding(5.dp)
                    .clickable(onClick = {
                        fileType = FileType.FOLDER
                    }), verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButton(
                    selected = fileType == FileType.FOLDER,
                    onClick = null
                )
                Spacer(modifier = Modifier.width(5.dp))
                Text(stringResource(id = R.string.cre_folder), color = MaterialTheme.colorScheme.onBackground)
            }
        }
        Row {
            Spacer(modifier = Modifier.weight(1f))
            UniformButton(onClick = {
                onConfirm(fileType)
            }, text = stringResource(id = R.string.manager_confirm))
            Spacer(modifier = Modifier.width(5.dp))
            UniformButton(onClick = onCancel, text = stringResource(id = R.string.manager_cancel))
        }
    }
}

@Composable
fun FinalCreateDialog(
    fileType: FileType,
    onConfirm: (String) -> Unit,
    onCancel: () -> Unit
) {
    var folderName by remember {
        mutableStateOf("")
    }
    var isError by remember { mutableStateOf(false) }
    BaseCreateDialog(
        title = if (fileType == FileType.FOLDER) stringResource(id = R.string.cre_creFolder) else stringResource(
            id = R.string.cre_creFile
        ),
        onDismissRequest = onCancel
    ) {
        TextField(
            value = folderName,
            label = {
                Text(
                    text = if (fileType == FileType.FOLDER) stringResource(id = R.string.cre_FolderName) else stringResource(
                        id = R.string.cre_FileName
                    ),
                    color = Color.Gray
                )
            },
            onValueChange = {
                folderName = it
                isError = it.isBlank()
            },
            isError = isError,
            supportingText = {
                if (isError) {
                    Text(
                        text = stringResource(id = R.string.cre_Name_not_empty),
                        color = MaterialTheme.colorScheme.error
                    )
                }
            },
            modifier = Modifier.fillMaxWidth(),
            colors = TextFieldDefaults.colors(unfocusedContainerColor = MaterialTheme.colorScheme.background)
        )
        Spacer(modifier = Modifier.height(5.dp))
        Row {
            Spacer(modifier = Modifier.weight(1f))
            UniformButton(onClick = {
                if (!isError && folderName != "") {
                    onConfirm(folderName)
                } else {
                    isError = true
                }
            }, text = stringResource(id = R.string.manager_confirm))
            Spacer(modifier = Modifier.width(5.dp))
            UniformButton(onClick = onCancel, text = stringResource(id = R.string.manager_cancel))
        }
    }
}

@Composable
fun CreateFileDialog(onConfirm: (NoteTemplateType) -> Unit, onCancel: () -> Unit) {
    var noteTemplateType by remember {
        mutableStateOf(NoteTemplateType.NO_TEMPLATE)
    }
    BaseCreateDialog(title = stringResource(id = R.string.cre_creNote), onDismissRequest = onCancel) {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier
                    .padding(5.dp)
                    .clickable(onClick = {
                        noteTemplateType = NoteTemplateType.NO_TEMPLATE
                    }), verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButton(
                    selected = noteTemplateType == NoteTemplateType.NO_TEMPLATE,
                    onClick = null
                )
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = stringResource(id = R.string.cre_No_template), color = MaterialTheme.colorScheme.onBackground)
            }
            Row(
                modifier = Modifier
                    .padding(5.dp)
                    .clickable(onClick = {
                        noteTemplateType = NoteTemplateType.CREATED_BY_AI
                    }), verticalAlignment = Alignment.CenterVertically
            ) {
                RadioButton(
                    selected = noteTemplateType == NoteTemplateType.CREATED_BY_AI,
                    onClick = null
                )
                Spacer(modifier = Modifier.width(5.dp))
                Text(stringResource(id = R.string.cre_custom_template), color = MaterialTheme.colorScheme.onBackground)
            }
        }
        Row {
            Spacer(modifier = Modifier.weight(1f))
            UniformButton(onClick = {
                onConfirm(noteTemplateType)
            }, text = stringResource(id = R.string.manager_confirm))
            Spacer(modifier = Modifier.width(5.dp))
            UniformButton(onClick = onCancel, text = stringResource(id = R.string.manager_cancel))
        }

    }
}
